import { Controller } from 'egg';
import { Result, File } from '../util';
import { SATISFY_SUFFIX, SATISFY_MAX_SIZE } from '../../constants/image';

const isValidateSuffix = (filename: string) => {
  const filenameSplitedArr = filename.split('.');
  const suffix = filenameSplitedArr[filenameSplitedArr.length - 1];
  const lowerSuffix = suffix.toLowerCase();

  return SATISFY_SUFFIX.includes(`.${lowerSuffix}`);
};

class FileController extends Controller {
  async upload() {
    const { ctx } = this;

    const stream = await ctx.getFileStream(
      {
        limits: { fileSize: SATISFY_MAX_SIZE }
      }
    );

    const { filename } = stream;

    if (!isValidateSuffix(filename)) {
      ctx.status = 422;
      ctx.body = new Result(undefined, '文件格式不对！');
      return;
    }

    const url = await File.saveImage(stream, filename);

    ctx.body = new Result({ url }, '上传文件成功！');
  }

  async viewPicture() {
    const { ctx } = this;

    const { filename } = ctx.query;

    const stream = File.readImage(filename);

    ctx.set('Content-type', 'image/jpeg');
    ctx.body = stream;
  }
}

module.exports = FileController;
